package me.yobol.greentable.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.yobol.greentable.bean.IngredientBean;
import me.yobol.greentable.bean.IngredientCommentBean;
import me.yobol.greentable.service.IngredientCommentService;
import me.yobol.greentable.service.IngredientService;
import me.yobol.greentable.service.UserService;

/**
 * @author Yobol
 *
 */
public class GetIngredientServlet extends HttpServlet {

	private static final long serialVersionUID = -3447250409925600751L;

	public GetIngredientServlet() {
		super();
	}

	public void init() throws ServletException {
		// Put your code here
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int ingredientId = (request.getParameter("ingredientId") == null) ? -1
				: Integer.parseInt(request.getParameter("ingredientId"));

		IngredientBean ingredient = IngredientService.getIngredientByIngredientId(ingredientId);
		String forwardUrl = null;
		if(ingredient != null){
			int scansCtr = ingredient.getIngredientScansCtr();
			if(IngredientService.updateIngredientScansCtr(ingredientId, ++scansCtr)){
				ingredient = IngredientService.getIngredientByIngredientId(ingredientId);
				
				String traderName = UserService.getUNameByUID(ingredient.getTraderId());

				request.getSession().setAttribute("ig", ingredient);
				request.getSession().setAttribute("traderName", traderName);
				
				List<IngredientCommentBean> comments = IngredientCommentService.getIgCommentByIgId(ingredientId);
				request.getSession().setAttribute("ic", comments);
				forwardUrl = "/pages/ingredient/ingredient.jsp";
			}
		}else{
			//give a feedback that no such dishes
		}
		
		RequestDispatcher rd = request.getRequestDispatcher(forwardUrl);
		rd.forward(request, response);
	}
	
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
